<template>
    <div class="activity-list-page">
        <el-card>
            <el-form :model="queryParams" inline>
                <el-form-item label="活动名">
                    <el-input v-model="queryParams.name" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="queryParams.status" clearable @change="handleQuery">
                        <el-option label="全部" value=""></el-option>
                        <el-option label="启用" value="1"></el-option>
                        <el-option label="停用" value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="small" icon="el-icon-search" @click="handleQuery">查询</el-button>
                    <el-button size="small" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
            <div class="flex_between" style="margin-bottom: 10px;">
                <div></div>
                <el-button type="primary" size="small" @click="goEditForm">新增活动</el-button>
            </div>
            <el-table :data="activityArr" border v-loading="loading">
                <el-table-column prop="status" align="center" label="启用状态" width="90">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status == 1" type="success">启用</el-tag>
                        <el-tag v-else type="danger">停用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="status" align="center" label="环境" width="90">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.env_type == 'prod'" type="success">生产</el-tag>
                        <el-tag v-else type="danger">开发</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="name" align="center" label="活动名" />
                <el-table-column prop="display_language" align="center" label="支持语言" width="150" />
                <el-table-column prop="start_time" align="center" label="支持版本" width="160">
                    <template slot-scope="scope">
                        <block v-if="scope.row.min_version">
                            {{ scope.row.min_version + '-' + scope.row.max_version }}
                        </block>
                        <block v-else>全量</block>
                    </template>
                </el-table-column>
                <el-table-column prop="start_time" label="开始时间" width="160">
                    <template slot-scope="scope">
                        {{ scope.row.start_time ? $options.filters.fmtDate(scope.row.start_time) : '-' }}
                    </template>
                </el-table-column>
                <el-table-column prop="end_time" label="结束时间" width="160">
                    <template slot-scope="scope">
                        {{ scope.row.end_time ? $options.filters.fmtDate(scope.row.end_time) : '-' }}
                    </template>
                </el-table-column>
                <el-table-column prop="updated_at" label="修改时间" width="160">
                    <template slot-scope="scope">
                        {{ scope.row.updated_at ? $options.filters.fmtDate(scope.row.updated_at) : '-' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="320" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="mini" type="success" v-if="scope.row.status == 0"
                            @click="handleStatus(scope.row, 1)" :loading="statusLoading[scope.row.id]">启用</el-button>
                        <el-button size="mini" type="danger" v-if="scope.row.status == 1"
                            @click="handleStatus(scope.row, 0)" :loading="statusLoading[scope.row.id]">停用</el-button>


                        <el-button size="mini" type="success" v-if="scope.row.env_type == 'prod'"
                            @click="handleEnv_type(scope.row, 'dev')"
                            :loading="statusLoading[scope.row.id]">生产</el-button>
                        <el-button size="mini" type="danger" v-if="scope.row.env_type == 'dev'"
                            @click="handleEnv_type(scope.row, 'prod')"
                            :loading="statusLoading[scope.row.id]">开发</el-button>

                        <el-button size="mini" type="warning" v-if="scope.row.logic_status == 1"
                            @click="handleLogicStatus(scope.row, 0)"
                            :loading="logicStatusLoading[scope.row.id]">删除</el-button>
                        <el-button size="mini" type="info" v-if="scope.row.logic_status == 0"
                            @click="handleLogicStatus(scope.row, 1)"
                            :loading="logicStatusLoading[scope.row.id]">恢复</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page"
                :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card>
        <!-- 活动新增/编辑弹窗 ↓↓↓ -->
        <el-dialog :visible.sync="dialogVisible" :title="form.id ? '编辑活动' : '新增活动'" width="1000px">
            <el-form :model="form" :rules="rules" ref="ruleForm" label-width="88px">
                <el-form-item label="活动名" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>
                <!-- 新增 最低版本号 -->
                <el-row>
                    <el-col :span="12"><el-form-item label="最低版本号" prop="min_version">
                            <el-input v-model="form.min_version" maxlength="20" placeholder="如 1.0.0" />
                        </el-form-item></el-col>
                    <el-col :span="12"><el-form-item label="最高版本号" prop="max_version">
                            <el-input v-model="form.max_version" maxlength="20" placeholder="如 2.1.5" />
                        </el-form-item></el-col>
                </el-row>

                <!-- 新增 最高版本号 -->

                <el-form-item label="活动时间" required>
                    <el-date-picker v-model="dateRange" type="datetimerange" start-placeholder="开始" end-placeholder="结束"
                        value-format="yyyy-MM-dd HH:mm:ss" style="width:100%" :editable="false" :clearable="false"
                        @change="onDateChange" />
                </el-form-item>
                <el-form-item label="入口配置" prop="entry_list">
                    <div class="entry-list-container">
                        <div v-for="(entry, entryIndex) in form.entry_list" :key="entryIndex" class="entry-item">
                            <div class="entry-card" style="padding: 15px;">
                                <div slot="header" class="entry-header-info">
                                    <span>入口 {{ entryIndex + 1 }}</span>
                                    <el-button v-if="form.entry_list.length > 1" type="text" size="small"
                                        @click="removeEntry(entryIndex)" style="color: #f56c6c;">
                                        <i class="el-icon-delete"></i> 删除入口
                                    </el-button>
                                </div>

                                <!-- 基本信息 -->
                                <div class="entry-basic-info">
                                    <el-row :gutter="15">
                                        <el-col :span="6">
                                            <el-form-item label="语言" :prop="`entry_list.${entryIndex}.lang`"
                                                :rules="[{ required: true, message: '必选', trigger: 'change' }]">
                                                <el-select v-model="entry.lang" placeholder="请选择" style="width:100%">
                                                    <el-option label="简体中文" value="zh" />
                                                    <el-option label="繁体中文" value="zh_TW" />
                                                    <el-option label="英文" value="en" />
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="9">
                                            <el-form-item label="图片链接" :prop="`entry_list.${entryIndex}.img`"
                                                :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
                                                <el-input v-model="entry.img" placeholder="图片链接" />
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="9">
                                            <el-form-item label="跳转链接" :prop="`entry_list.${entryIndex}.link`"
                                                :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
                                                <el-input v-model="entry.link" placeholder="跳转链接" />
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row :gutter="15" style="margin-top: 10px;">
                                        <el-col :span="12">
                                            <el-form-item :label="`动态参数1`" :prop="`entry_list.${entryIndex}.paramOne`">
                                                <el-input v-model="entry.paramOne" placeholder="请输入参数1" />
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item :label="`动态参数2`" :prop="`entry_list.${entryIndex}.paramTwo`">
                                                <el-input v-model="entry.paramTwo" placeholder="请输入参数2" />
                                            </el-form-item>
                                        </el-col>
                                    </el-row>

                                </div>

                                <!-- 奖励配置 -->
                                <div class="rewards-section">
                                    <div class="rewards-header">
                                        <span class="rewards-title">奖励配置</span>
                                        <el-button type="primary" size="mini" plain @click="addReward(entryIndex)">
                                            <i class="el-icon-plus"></i> 新增奖励
                                        </el-button>
                                    </div>

                                    <div v-if="entry.rewards && entry.rewards.length > 0" class="rewards-list">
                                        <div v-for="(reward, rewardIndex) in entry.rewards" :key="rewardIndex"
                                            class="reward-item">
                                            <el-row :gutter="10" align="middle">
                                                <el-col :span="7">
                                                    <el-form-item :label="`奖励名称`"
                                                        :prop="`entry_list.${entryIndex}.rewards.${rewardIndex}.reward_name`"
                                                        :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
                                                        <el-input v-model="reward.reward_name" placeholder="请输入奖励名称" />
                                                    </el-form-item>
                                                </el-col>
                                                <el-col :span="7">
                                                    <el-form-item :label="`momo币`"
                                                        :prop="`entry_list.${entryIndex}.rewards.${rewardIndex}.momo_amount`"
                                                        :rules="[
                                                            { required: true, message: '必填', trigger: 'blur' },
                                                            { type: 'number', min: 0, message: '不能小于0', trigger: 'blur' }
                                                        ]">
                                                        <el-input-number v-model="reward.momo_amount" :min="0"
                                                            :precision="0" controls-position="right" style="width:100%"
                                                            placeholder="请输入momo币数量" />
                                                    </el-form-item>
                                                </el-col>
                                                <el-col :span="7">
                                                    <el-form-item :label="`翻译时长`"
                                                        :prop="`entry_list.${entryIndex}.rewards.${rewardIndex}.trans_duration`"
                                                        :rules="[{ required: true, message: '必填', trigger: 'blur' }, { type: 'number', min: 0, message: '不能小于0', trigger: 'blur' }]">
                                                        <el-input-number v-model="reward.trans_duration" :min="0"
                                                            :precision="0" controls-position="right" style="width:100%"
                                                            placeholder="请输入翻译时长（分钟）" />
                                                    </el-form-item>
                                                </el-col>
                                                <el-col :span="3" style="text-align: right;">
                                                    <el-button v-if="entry.rewards.length > 1" type="danger" size="mini"
                                                        @click="removeReward(entryIndex, rewardIndex)">
                                                        删除
                                                    </el-button>
                                                </el-col>
                                            </el-row>
                                        </div>
                                    </div>

                                    <div v-else class="no-rewards">
                                        <el-alert title="暂无奖励配置，请点击上方按钮新增" type="info" :closable="false"
                                            show-icon></el-alert>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div style="margin-top: 15px; text-align: center;">
                        <el-button type="primary" plain @click="addEntry">
                            <i class="el-icon-plus"></i> 新增入口
                        </el-button>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveOrUpdate" :loading="saveLoading">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios'
import moment from 'moment'

export default {
    data() {
        return {
            statusLoading: {},        // 一定是 {}
            logicStatusLoading: {},   // 一定是 {}
            saveLoading: false,
            loading: false,
            activityArr: [],
            total: 0,
            queryParams: {
                name: '',
                status: '',
                page: 1,
                size: 10,
            },
            dialogVisible: false,
            dateRange: [],
            form: {
                id: '',
                name: '',
                start_time: '',
                end_time: '',
                entry_list: [],
                min_version: '',// 新增
                max_version: '',// 新增
            },
            rules: {
                name: [{ required: true, message: '必填', trigger: 'blur' }],
                min_version: [
                    { validator: this.validateVersionFormat, trigger: 'blur' }
                ],
                max_version: [
                    { validator: this.validateVersionFormat, trigger: 'blur' }
                ],
                entry_list: [
                    {
                        required: true,
                        type: 'array',
                        min: 1,
                        message: '至少配置一个入口',
                        trigger: 'blur'
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (!Array.isArray(value) || !value.length) {
                                return callback(new Error("至少配置一个入口"));
                            }
                            for (let i = 0; i < value.length; i++) {
                                const entry = value[i];
                                if (!entry.lang || !entry.img || !entry.link) {
                                    return callback(new Error(`第${i + 1}个入口的语言/图片/链接不能为空`));
                                }
                                if (!entry.rewards || !Array.isArray(entry.rewards) || entry.rewards.length === 0) {
                                    return callback(new Error(`第${i + 1}个入口至少需要配置一个奖励`));
                                }
                                for (let j = 0; j < entry.rewards.length; j++) {
                                    const reward = entry.rewards[j];
                                    if (!reward.reward_name || reward.momo_amount === undefined || reward.momo_amount === null || reward.momo_amount === '') {
                                        return callback(new Error(`第${i + 1}个入口的第${j + 1}个奖励的名称和momo币数量不能为空`));
                                    }
                                    if (reward.momo_amount < 0) {
                                        return callback(new Error(`第${i + 1}个入口的第${j + 1}个奖励的momo币数量不能小于0`));
                                    }
                                    if (!reward.reward_name || reward.momo_amount === undefined || reward.momo_amount === null || reward.momo_amount === '' || !reward.trans_duration) {
                                        return callback(new Error(`第${i + 1}个入口的第${j + 1}个奖励的名称、momo币、翻译时长不能为空`));
                                    }
                                }
                            }
                            callback();
                        },
                        trigger: "blur"
                    }
                ]
            }

        }
    },
    created() {
        this.getList()
    },
    filters: {
        fmtDate(dt) {
            return dt ? moment(dt).format("YYYY-MM-DD HH:mm:ss") : "";
        }
    },
    methods: {
        // 1. 获取分页活动列表
        async getList() {
            this.loading = true;
            try {
                // 保证参数名和后端一致
                let params = {
                    ...this.queryParams,
                };
                let { data: res } = await axios.post('https://xiaoshuchengzhang.com/node/Transir/getActivityList', params);
                this.loading = false;
                if (res.code === 0) {
                    this.activityArr = res.data.list
                    this.total = res.data.total
                } else {
                    this.$message.error(res.msg || '获取失败')
                }
            } catch (e) {
                this.loading = false
                this.$message.error(e.message || '获取失败')
            }
        },
        handleQuery() {
            this.queryParams.page = 1
            this.getList()
        },
        resetQuery() {
            this.queryParams = { name: '', status: '', page: 1, size: 10 };
            this.getList()
        },
        // 2. 新增/编辑活动弹窗
        goEditForm() {
            this.form = {
                id: '',
                name: '',
                start_time: '',
                end_time: '',
                entry_list: [],
            };
            this.dateRange = [];
            this.dialogVisible = true;
        },
        // 编辑按钮
        handleEdit(row) {
            this.form = {
                ...row,
                entry_list: row.entry_list ? (typeof row.entry_list === 'string' ? JSON.parse(row.entry_list) : row.entry_list) : [],
            };
            // 确保每个entry都有完整的字段和rewards数组
            this.form.entry_list = this.form.entry_list.map(entry => ({
                lang: entry.lang || '',
                img: entry.img || '',
                link: entry.link || '',
                paramOne: entry.paramOne || '', // 新增
                paramTwo: entry.paramTwo || '', // 新增
                rewards: Array.isArray(entry.rewards)
                    ? entry.rewards.map(reward => ({
                        reward_name: reward.reward_name || '',
                        momo_amount: reward.momo_amount || 0,
                        trans_duration: reward.trans_duration || '',
                    }))
                    : []
            }));

            const start = row.start_time ? moment(row.start_time).format("YYYY-MM-DD HH:mm:ss") : '';
            const end = row.end_time ? moment(row.end_time).format("YYYY-MM-DD HH:mm:ss") : '';
            this.dateRange = [start, end];
            this.form.start_time = start;
            this.form.end_time = end;
            this.dialogVisible = true;
        },
        // 入口相关
        addEntry() {
            this.form.entry_list.push({
                lang: '',
                img: '',
                link: '',
                paramOne: '', // 新增
                paramTwo: '', // 新增
                rewards: [{ reward_name: '', momo_amount: 0 }]
            });
        },
        removeEntry(entryIndex) {
            this.form.entry_list.splice(entryIndex, 1);
        },
        // 奖励相关
        addReward(entryIndex) {
            if (!this.form.entry_list[entryIndex].rewards) {
                this.$set(this.form.entry_list[entryIndex], 'rewards', []);
            }
            // this.form.entry_list[entryIndex].rewards.push({ reward_name: '', momo_amount: 0 });
            this.form.entry_list[entryIndex].rewards.push({ reward_name: '', momo_amount: 0, trans_duration: '' });

        },
        removeReward(entryIndex, rewardIndex) {
            this.form.entry_list[entryIndex].rewards.splice(rewardIndex, 1);
        },
        onDateChange(val) {
            // 分拆到form
            if (Array.isArray(val) && val.length == 2) {
                this.form.start_time = val[0]
                this.form.end_time = val[1]
            }
        },
        // 3. 保存新增/编辑
        async saveOrUpdate() {
            this.saveLoading = true;
            try {
                await this.$refs.ruleForm.validate();
            } catch {
                this.saveLoading = false;
                return;
            }
            // 跨字段判断：只要有一个填了，另一个也要填且都合法
            const minVer = this.form.min_version;
            const maxVer = this.form.max_version;
            const versionPattern = /^\d+\.\d+\.\d+$/;
            if ((!!minVer && !maxVer) || (!minVer && !!maxVer)) {
                this.$message.error('最低和最高版本号需同时填写，且格式为 x.x.x');
                this.saveLoading = false;
                return;
            }
            if (minVer && !versionPattern.test(minVer)) {
                this.$message.error('最低版本号格式错误，应为 x.x.x');
                this.saveLoading = false;
                return;
            }
            if (maxVer && !versionPattern.test(maxVer)) {
                this.$message.error('最高版本号格式错误，应为 x.x.x');
                this.saveLoading = false;
                return;
            }
            // 自动提取所有lang拼接display_language
            const display_language = Array.from(new Set(this.form.entry_list.map(e => e.lang))).filter(Boolean).join(',');
            const params = {
                ...this.form,
                display_language
            };
            // 字段防止穿透为undefined
            params.entry_list = this.form.entry_list;

            try {
                let { data: res } = await axios.post('https://xiaoshuchengzhang.com/node/Transir/saveActivity', params);
                if (res.code === 0) {
                    this.$message.success('保存成功');
                    this.dialogVisible = false;
                    this.getList();
                    this.saveLoading = false;
                } else {
                    this.$message.error(res.msg || '保存失败');
                    this.saveLoading = false;
                }
            } catch (e) {
                this.$message.error(e.message || '保存失败');
                this.saveLoading = false;
            }
        },
        validateVersionFormat(rule, value, callback) {
            // 允许为空
            if (!value || value === '') {
                callback();
                return;
            }
            const versionPattern = /^\d+\.\d+\.\d+$/;
            if (!versionPattern.test(value)) {
                callback(new Error('版本号格式不正确，应为 x.x.x'));
            } else {
                callback();
            }
        },
        // 4. 启用/停用活动
        async handleStatus(row, tarStatus) {
            const actionText = tarStatus == 1 ? "启用" : "停用";
            this.$confirm(`此操作将${actionText}该活动，是否继续？`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(async () => {
                this.$set(this.statusLoading, row.id, true);
                try {
                    let { data: res } = await axios.post('https://xiaoshuchengzhang.com/node/Transir/updateActivityStatus', {
                        id: row.id,
                        status: tarStatus
                    });
                    if (res.code === 0) {
                        this.$message.success(`${actionText}成功`);
                        this.getList();
                    } else {
                        this.$message.error(res.msg || `${actionText}失败`);
                    }
                } catch (e) {
                    this.$message.error(e.message || `${actionText}失败`);
                }
                this.$set(this.statusLoading, row.id, false);
            }).catch(() => {
                // 用户取消后保证按钮不在loading
                this.$set(this.statusLoading, row.id, false);
            });
        },
        // 4. 切换生产开发
        async handleEnv_type(row, tarStatus) {
            const actionText = tarStatus == 'dev' ? "切换为开发环境" : "切换为生产环境";
            this.$confirm(`此操作将该活动${actionText}，是否继续？`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(async () => {
                this.$set(this.statusLoading, row.id, true);
                try {
                    let { data: res } = await axios.post('https://xiaoshuchengzhang.com/node/Transir/updateActivityEnv_type', {
                        id: row.id,
                        status: tarStatus
                    });
                    if (res.code === 0) {
                        this.$message.success(`${actionText}成功`);
                        this.getList();
                    } else {
                        this.$message.error(res.msg || `${actionText}失败`);
                    }
                } catch (e) {
                    this.$message.error(e.message || `${actionText}失败`);
                }
                this.$set(this.statusLoading, row.id, false);
            }).catch(() => {
                // 用户取消后保证按钮不在loading
                this.$set(this.statusLoading, row.id, false);
            });
        },
        // 5. 逻辑删除/恢复
        async handleLogicStatus(row, logicStatus) {
            const isDel = logicStatus == 0;
            const actionText = isDel ? "删除" : "恢复";
            this.$confirm(`此操作将${actionText}该活动，是否继续？`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: isDel ? "error" : "info"
            }).then(async () => {
                this.$set(this.logicStatusLoading, row.id, true);
                try {
                    let { data: res } = await axios.post('https://xiaoshuchengzhang.com/node/Transir/updateActivityLogicStatus', {
                        id: row.id,
                        logic_status: logicStatus
                    });
                    if (res.code === 0) {
                        this.$message.success(`${actionText}成功`);
                        this.getList();
                    } else {
                        this.$message.error(res.msg || `${actionText}失败`);
                    }
                } catch (e) {
                    this.$message.error(e.message || `${actionText}失败`);
                }
                this.$set(this.logicStatusLoading, row.id, false);
            }).catch(() => {
                this.$set(this.logicStatusLoading, row.id, false);
            });
        },
    }
}
</script>

<style scoped>
.flex_between {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.entry-list-container {
    max-width: 100%;
}

.entry-item {
    margin-bottom: 20px;
}

.entry-card {
    border: 1px solid #e4e7ed;
    border-radius: 8px;
}

.entry-header-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
}

.entry-basic-info {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f2f5;
}

.rewards-section {
    background: #fafafa;
    padding: 15px;
    border-radius: 6px;
}

.rewards-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.rewards-title {
    font-weight: 600;
    color: #303133;
    font-size: 14px;
}

.rewards-list {
    max-height: 400px;
    overflow-y: auto;
}

.reward-item {
    background: white;
    padding: 15px;
    border-radius: 6px;
    margin-bottom: 10px;
    border: 1px solid #e4e7ed;
}

.reward-item:last-child {
    margin-bottom: 0;
}

.no-rewards {
    text-align: center;
    padding: 20px;
}

.el-form-item {
    margin-bottom: 15px;
}

.el-input input::placeholder,
.el-select .el-input__inner::placeholder,
.el-input-number input::placeholder {
    color: #cbcbcb !important;
}

/* 响应式调整 */
@media (max-width: 1200px) {
    .entry-basic-info .el-col {
        margin-bottom: 10px;
    }

    .reward-item .el-row .el-col {
        margin-bottom: 10px;
    }
}
</style>